package testJdk.commonUse.collections.list.sort;

import lombok.Data;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * lambda比较，Comparator比较，自定义Comparator比较
 */
public class TestSort {

    @Data
    static class Student {
        Integer id;
        String name;


        public Student(int id, String name) {
            this.id = id;
            this.name = name;
        }

    }

    private List<Student> studentList;
    private List<Integer> intList;

    @Before
    public void testBefore() {
        Integer[] intArr = new Integer[]{1, 3, 2, 4};
        intList = Arrays.asList(intArr);

        studentList = new ArrayList<>();
        Student student01 = new Student(2, "bb");
        Student student02 = new Student(1, "aa");
        Student student03 = new Student(3, "aa");
        Student student04 = new Student(2, "aa");

        studentList.add(student01);
        studentList.add(student02);
        studentList.add(student03);
        studentList.add(student04);
    }


    /**
     * 直接用lambda排序
     */
    @Test
    public void test01() {
        System.out.println(intList);
        // 简单排序
        intList.sort((a, b) -> (int) a - (int) b);
        System.out.println(intList);

        System.out.println(studentList);

        // 对象排序，只按照id排序
        studentList.sort((a, b) -> a.getId() - b.getId());
        System.out.println(studentList);

        // 对象排序，先按照id排序，id相同时再按照name排序
        studentList.sort((a, b) -> !a.getId().equals(b.getId())
                ? a.getId() - b.getId() : a.getName().compareTo(b.getName()));
        System.out.println(studentList);


    }

    /**
     * 使用排序器
     */
    @Test
    public void test02() {
        System.out.println(intList);
        // 简单排序
        intList.sort(Comparator.comparingInt(a -> (int) a));
        System.out.println(intList);

        System.out.println(studentList);

        // 使用排序器对复杂对象排序
        // 只按照id排序
        studentList.sort(Comparator.comparing(Student::getId));
        System.out.println(studentList);

        // 先按照id排序，id相同时再按照name排序
        studentList.sort(Comparator.comparing(Student::getId)
                .thenComparing(Student::getName));
        System.out.println(studentList);
    }


    /**
     * 对复杂对象使用自定义比较器排序
     */
    @Test
    public void test03() {
        System.out.println(studentList);
        // 先按照id排序，id相同时再按照name排序
        studentList.sort(new StudentComparator());
        System.out.println(studentList);
    }
}

/**
 * 自定义比较器
 */
class StudentComparator implements Comparator<TestSort.Student> {

    // 重写compare方法
    @Override
    public int compare(TestSort.Student o1, TestSort.Student o2) {
        // 先按照id排序，id相同时再按照name排序
        if (!o1.getId().equals(o2.getId())) {
            return o1.getId() < o2.getId() ? -1 : 1;
        } else {
            return o1.getName().compareTo(o2.getName());
        }
    }
}
